import { useState, useImperativeHandle, useEffect, useRef } from 'react';
import api from './api';
import { getFileTypeIconSvg, useEvents, InbizIcon } from '@inbiz/utils';
import { getMessage, TextWidget } from '@inbiz/react';
import type { inbiz } from '@inbiz/core';
import { CloseOutlined, CloseCircleOutlined } from '@ant-design/icons';
import DocConfig from '../DocSelect';
import { isArray } from 'lodash';
import { getDocumentInfoByFile, getDocumentInfoByFolder } from './service';
import './index.less';

export type ModeType = 'SelectFolder' | 'SelectFile';

type IProps = {
  mode: ModeType;
  isTpl: boolean;
  lang: string;
  value?: any;
  viewMode?:string;
  emit: {
    /**首次渲染时触发*/
    (type: 'onload'): void;
    /**select事件*/
    (type: 'onSelect', data: any[], changeData?: any[]): void;
    /**值改变事件*/
    (type: 'onChange', data: any[]): void;
    /**打开弹框时执行*/
    (type: 'onOpen', data?: any[]): void;
    /**关闭弹框时执行*/
    (type: 'onClose', data: any[]): void;
    /**查看文件时执行*/
    (type: 'onFilePreview', fileId: string): void;
  };
  inbiz: inbiz;
  callBackEvents?: {
    onBeforeOpen?: (type: string, data: any[]) => boolean | undefined;
    onBeforeClose?: (type: string, data: any[]) => boolean | undefined;
  };
  placeholder?: string;
  showPersonalLibrary?: boolean;
  multiple: boolean;
  defaultValue?: any;
  topFolder?: any;
  columnField: [];
  thumbnail: boolean;
  readOnly: boolean;
  disabled: boolean;
  onChange: Function;
  className: string;
  originValue: any;
  storageConfig: any;
  controlId: any;
  childModelConfig: boolean;
  remoteServer?: {
    //第三方服务器， 用于文件摆渡
    url: string;
    token: string;
  };
  componentIsInline?: boolean;
  inlineValue?: string;
};

const SelectDoc = (props: IProps, ref: any) => {
  const { mode, thumbnail, readOnly, multiple, disabled, value,viewMode } = props;
  // const [value,$value]=useState<any>(oldValue)
  const [configEvents] = useEvents<{
    onBeforeOpen?: (type: string, data: any[]) => boolean | undefined;
  }>(props.callBackEvents, props.emit);
  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents, props),
    }),
    [props.value, multiple],
  );

  // useEffect(()=>{
  //   initValue()
  // },[props.value])

  // const initValue=async ()=>{
  //   const first=props.value?.[0]
  //   if(typeof first === 'string'){
  //     // const _mode=inbiz(controlId).componentType;
  //     const res=await getInlineInitValue(mode,props)
  //     $value(res??[])
  //   }
  // }

  useEffect(() => {
    props.emit?.('onload');
  }, []);

  const [visibleModal, setVisibleModal] = useState<boolean>(false); //模态框显隐
  const [selectNum, setSelectNum] = useState<number>(0); //文件/文件夹选择的数量
  const [selectData, setSelectData] = useState<any[]>([]); //选中的数据

  const delAll = async () => {
    if (readOnly || disabled || props.inbiz?.browser?.designer) {
      return;
    }

    setSelectData([]);
    setSelectNum(0);
    props.onChange([]);
    childrenRef.current?.setSelectedRowKeys([]);
  };

  const delList = async (index: number) => {
    if (readOnly || disabled || props.inbiz?.browser?.designer) {
      return;
    }

    let oldSelectData = [...selectData];
    oldSelectData.splice(index, 1);
    setSelectData(oldSelectData);
    setSelectNum(oldSelectData.length);
    props.onChange(oldSelectData);

    childrenRef.current?.setSelectedRowKeys((v: any) => {
      let oldV = [...v];
      oldV.splice(index, 1);
      return oldV;
    });
  };

  const lookFile = (fileId: any) => {
    if (mode !== 'SelectFile') {
      return;
    }

    props.emit?.('onFilePreview', fileId);
    let url = props.remoteServer?.url || '';
    if (url[url.length - 1] === '/') {
      url = url.slice(0, -1);
    }
    window.open(url + `/preview.html?fileid=${fileId}`);
  };

  useEffect(() => {
    if (value?.length > 0) {
      setSelectData(value);
      setSelectNum(value?.length);
    } else {
      setSelectNum(0);
      setSelectData([]);
    }
  }, [value]);


  const inlineMultipleData = (item, index) => (
    <div
      className={`selectListBox ${readOnly || disabled ? '' : 'selectListBoxhover'}`}
      key={item.key}
      style={{
        color: 'var(--inbiz-color-heading)',
        fontSize: 'var(--inbiz-font-size-base)',
      }}
    >
      <div className="selectListName" onClick={() => lookFile(item.key)}>
        <div className="listName" title={item.name}>
          {item.name}
        </div>
      </div>
      <div className="delList">
        <CloseCircleOutlined className="delIcons" onClick={() => delList(index)} />
        {/* <CloseOutlined  /> */}
      </div>
    </div>
  );

  const designList = props.componentIsInline ? (
    <div className={props.className}>
      {selectData.map((item, index) => inlineMultipleData(item, index))}
    </div>
  ) : (
    <div className="designList" style={viewMode=='look'?{border:'none',marginTop:'-4px'}:{}} >
      {viewMode!='look'&&<div className="designListUp" style={{ fontSize: 12 }}>
        <div className="designSelectNum">
          {`${getMessage('SelectDoc.selected')}${mode === 'SelectFile' ? getMessage('SelectDoc.file') : getMessage('SelectDoc.folder')
            }，${getMessage('SelectDoc.totalBefore')}`}
          <span style={{ color: 'var(--inbiz-color-primary)' }}>{selectNum}</span>
          {`${getMessage('SelectDoc.totalAfter')}`}
        </div>
        <div className="designDel" onClick={delAll}>
          <InbizIcon
            type={'icon-ic-tree-huishouzhan'}
            style={{ marginRight: 6, color: 'var(--inbiz-color-primary)' }}
          />
          <span>
            <TextWidget>SelectDoc.removeAll</TextWidget>
          </span>
        </div>
      </div>}
      <div className={thumbnail ? 'selectImgList' : 'selectList'} style={{marginTop:thumbnail&&viewMode=='look'?'-24px':''}}>
        {selectData.map((item, index) => (
          <div
            className={`selectListBox ${readOnly || disabled ? '' : 'selectListBoxhover'}`}
            key={item.key}
            style={{
              color: 'var(--inbiz-color-heading)',
              fontSize: 'var(--inbiz-font-size-base)',
            }}
          >
            <div className="selectListName" onClick={() => lookFile(item.key)}>
              <div className="fileIcons">
                <img
                  src={
                    mode === 'SelectFile'
                      ? getFileTypeIconSvg(item.name)
                      : getFileTypeIconSvg('.folder')
                  }
                />
              </div>
              <div className="listName" style={{color:viewMode=='look' ?'var(--inbiz-color-heading)':''}} title={item.name}>
                {item.name}
              </div>
            </div>
            {viewMode!='look'&&<div className="delList">
              <CloseOutlined className="delIcons" onClick={() => delList(index)} />
            </div>}
          </div>
        ))}
      </div>
    </div>
  );

  const inlineSingleData = (item) => (
    <div style={{ display: 'flex' }}>
      <div
        className={`radioNameBox`}
        onClick={() => {
          lookFile(item.key);
        }}
      >
        <div className="radioName" title={item.name}>
          {item.name}
        </div>
      </div>
      <div className="radioDelBox">
        <CloseCircleOutlined
          className="radioDelIcons"
          onClick={() => {
            if (readOnly || disabled || props.inbiz?.browser?.designer) {
              return;
            }
            setSelectData([]);
            props.onChange([]);
          }}
        />
      </div>
    </div>
  );

  const radio = (selectData ?? []).map((item) =>
    props.componentIsInline ? (
      inlineSingleData(item)
    ) : (
      <div
        className={
          thumbnail
            ? `radioSelectImg ${readOnly || disabled ? '' : 'radioSelectImgHover'}`
            : `radioSelectList ${readOnly || disabled || props.inbiz?.browser?.designer ? '' : 'radioSelectListHover'
            }`
        }
        style={{border:viewMode=='look'?'none':'solid 1px #ddd'}}
        key={item.key}
      >
        <div
          className={`radioNameBox`}
          onClick={() => {
           lookFile(item.key);
          }}
        >
          <div className="radioImgBox">
            <img
              src={
                mode === 'SelectFile'
                  ? getFileTypeIconSvg(item.name)
                  : getFileTypeIconSvg('.folder')
              }
            />
          </div>
          <div className="mask"></div>
          <div className="radioName" title={item.name}>
            {item.name}
          </div>
        </div>
        {viewMode!='look'&&<div className="radioDelBox">
          <CloseOutlined
            className="radioDelIcons"
            onClick={() => {
              if (readOnly || disabled || props.inbiz?.browser?.designer) {
                return;
              }
              setSelectData([]);
              props.onChange([]);
            }}
          />
        </div>}
      </div>
    ),
  );

  const childrenRef = useRef<any>();
  return (
    <div className={`selectedMain ${props.className || ''}`}>
      {selectData.length > 0 && !multiple ? (
        radio
      ) : (
        <div
          className={`selectButton ${readOnly || disabled ? 'selectButtonForbid' : 'selectButtonHover'
            }`}
            style={{display:viewMode=='look'?'none':''}}
          onClick={async () => {
            if (readOnly || disabled || props.inbiz?.browser?.designer) {
              return;
            }

            let result = (await configEvents.current?.onBeforeOpen?.('open', selectData)) ?? true;
            if (!result) {
              return;
            }

            props.emit?.('onOpen', selectData);

            setVisibleModal(true);
          }}
        >
          <div className="selectText">
            <InbizIcon
              type={'icon-xuanzewenjian'}
              style={{
                marginRight: '6px',
                color: `${readOnly || disabled ? '#b7b7b7' : 'var(--inbiz-color-primary)'}`,
              }}
            ></InbizIcon>
            <span>{props.placeholder}</span>
          </div>
        </div>
      )}
      <DocConfig
        {...props}
        ref={childrenRef}
        visibleModal={visibleModal}
        setVisibleModal={setVisibleModal}
        selectNum={selectNum}
        setSelectNum={setSelectNum}
        selectData={selectData}
        setSelectData={setSelectData}
      />
      {selectData.length > 0 && multiple ? designList : null}
    </div>
  );
};

SelectDoc.originValueFormat = (value: string, props: IProps) => {
  let mode = props.inbiz(props.controlId).__componentname;
  let nextValue = value;
  nextValue = isArray(nextValue) ? nextValue.map((ele) => ele.fileid).join(',') : nextValue;
  if (mode.includes?.('SelectFile$') && nextValue?.length !== 0) {
    return getDocumentInfoByFile(nextValue, props).then((res) => {
      return (
        res?.map?.((item: any, index: number) => {
          return {
            ...item,
            fileid: item.fileid,
            key: item.fileid,
            // id: index,
            name: item.filename,
          };
        }) || []
      );
    });
  } else if (nextValue?.length !== 0) {
    return getDocumentInfoByFolder(nextValue, props).then((res) => {
      return (
        res?.map?.((item: any, index: number) => {
          return {
            ...item,
            folderid: item.folderid,
            key: item.folderid,
            // id: index,
            name: item.foldername,
            // foldername: item.foldername,
            // foldersize: item.foldersize,
            // parentfolderid: item.parentfolderid,
            // address: `${item.relativepath?.split('\\').join('/')}`,
          };
        }) || []
      );
    });
  }
};

export default SelectDoc;
export type { api };
export type { IProps };
